#include "main.h"
#include "sha_thread.h"
#include "atsha204.h"
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "zlog.h"
#include "usr_cfg.h"
#include "usr_typedef.h"

#define ATSHA204_DEV						"/dev/atsha204a"			//SHA加密设备

extern sys_cfg_info		sys_cfg;

//版权校验线程
void *sha_verify_thread(void *arc)
{
	thread_status *s = NULL;
	int fd, rand0,rand1;
	digest_t digest;

	printf("copyright check thread is starting!\n");
	
	if(arc == NULL)
		return NULL;

	s = (thread_status*)arc;
	s->status = TS_ALIVE;

	sleep(SHA_VERIFY_DELAY);			//延时启动

	fd = open(ATSHA204_DEV, O_RDWR);
    if(fd < 0){
		dzlog_error(ATSHA204_DEV "open failed!");
		perror(ATSHA204_DEV"open failed!\n");
		s->status = TS_TERMINATED;
		pthread_exit(arc);
    }

	while (s->status) {
		rand0 = rand() % 12;						//key rand返回正数
		rand1 = rand() % 12;						//num rand返回正数
		atsha204_verify(fd,	rand0, rand1, &digest);
		for (unsigned char i = 0; i < 32; i++) {
			if (digest.host_digest[i] != digest.digest[i]) {
				dzlog_notice("#####the device is not authorized!!!#####");
				dzlog_notice("#######please contact the supplier#######");
				exit(EXIT_FAILURE);
			}
		}
		
		if (sys_cfg.debug == ON)
			printf("intellectual property verification is successful\n");
		
		sleep(SHA_VERIFY_DELAY);
	}
	
	close(fd);
	dzlog_notice("copyright check thread exit!!!");
	printf("copyright check thread exit!!!\n");
	pthread_exit((void *)0);
}



